﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ClassLibrary1.Templates
{
    public abstract class TemplatesBase
    {
        public TemplatesBase(string fileExt)
        {
            FileExt = fileExt;
        }

        /// <summary>
        /// 文件名后缀
        /// </summary>
        public string FileExt { get; set; }

        /// <summary>
        /// 文件生成的路径
        /// </summary>
        public string filePath
        {
            get
            {
                return Entrance.attrfilePath + "\\" + Entrance.attrdbTableName + "\\" + FileExt;
            }
        }

        /// <summary>
        /// 命名空间
        /// </summary>
        public virtual string namespacestr
        {
            get
            {
                return Entrance.attrnamespacestr + "." + FileExt;
            }
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        public abstract void SaveFile(List<EntityAttrList> list);

        public void CreateFile(string txtTableName, string txtContent, string fileExt = "")
        {
            if (!File.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            StreamWriter expr_F7 = new StreamWriter(Path.Combine(filePath, txtTableName + (string.IsNullOrWhiteSpace(fileExt) ? FileExt : fileExt) + ".cs"), false, Encoding.Default);
            expr_F7.Write(txtContent);
            expr_F7.Flush();
            expr_F7.Close();
            expr_F7.Dispose();
        }

        public string GetPrimaryKey(List<EntityAttrList> list)
        {
            var entity = list.FirstOrDefault(i => i.主键 == 1);
            if (entity == null)
            {
                entity = list.FirstOrDefault(i => i.Sort == 1);
            }
            if (entity == null)
            {
                entity = new EntityAttrList();
            }
            return entity.TypeName;
        }

    }
}
